<?php

namespace Openfennec\CoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;
use Openfennec\CoreBundle\Entity\Site;
use Openfennec\CoreBundle\Entity\User;

class DefaultController extends Controller {
    public function homepageAction (){
        $site = $this->getDoctrine()->getRepository("OpenfennecCoreBundle:Site")->find(1);
        
        return $this->render("OpenfennecCoreBundle:Default:index.html.twig", array(
            "site" => $site,
        ));
    }
    
    public function loginAction (Request $request){
        $site = $this->getDoctrine()->getRepository("OpenfennecCoreBundle:Site")->find(1);
        
        $session = $request->getSession();
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }
        
        return $this->render("OpenfennecCoreBundle:Default:login.html.twig", array(
            "site" => $site,
            "last_username" => $session->get(SecurityContext::LAST_USERNAME),
            "error" => $error,
        ));
    }
    
    public function signupAction (Request $request){
        $site = $this->getDoctrine()->getRepository("OpenfennecCoreBundle:Site")->find(1);
        
        $user = new User();
        
        $form = $this->createFormBuilder($user)
            ->add("username", "text", array("label" => "user.label.username"))
            ->add("nick", "text", array("label" => "user.label.nick"))
            ->add("email", "email", array("label" => "user.label.email"))
            ->add("password", "password", array("label" => "user.label.password"))
            ->add("signup", "submit", array("label" => "user.action.sign_up"))
            ->getForm();
        
        if ($request->getMethod() == "POST"){
            $form->handleRequest($request);
            if ($form->isValid()) {
                $orm = $this->getDoctrine()->getEntityManager();
                $user = $form->getData();
                
                $factory = $this->get("security.encoder_factory");
                $encoder = $factory->getEncoder($user);
                $password = $encoder->encodePassword($user->getPassword(), $user->getSalt());
                $user->setPassword($password);
                
                $orm->persist($user);
                $orm->flush();
                return $this->redirect($this->generateUrl("openfennec_index"));
            }
        }
        
        return $this->render("OpenfennecCoreBundle:Default:signup.html.twig", array(
            "site" => $site,
            "form" => $form->createView(),
        ));
    }
}
